package xyz.xiangyushui.util.dataBase;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;

public class SqlFileParser {
	/**
	 * return all the sql commands from .sql file;
	 * @param sqlFile
	 * @return an array contains all sql commands from the giving .sql file
	 */
	public static String[] loadSqlFile(File sqlFile) {
		List<String> sqlList = new LinkedList<String>();
		Scanner s = null;
		try {
			s = new Scanner(new FileInputStream(sqlFile));
			s.useDelimiter("^");
			String sqlStr = s.hasNext() ? s.next() : "";
			String[] sqlArr = sqlStr.split("(;\\s*\\r\\n)|(;\\s*\\n)");
			for (String sql : sqlArr) {
				String sqlNew = sql.replaceAll("--.*", "").trim();
				if (!sqlNew.equals("")) {
					//System.out.println("line:"+sqlNew);
					sqlList.add(sql);
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (s != null)
				s.close();
		}
		return (String[]) sqlList.toArray(new String[sqlList.size()]);
	}
}
